package net.courier.remoting.client;

import java.lang.reflect.Method;

import org.apache.commons.pool.impl.GenericObjectPool;

import net.courier.remoting.protocol.RequestDatagram;
import net.courier.remoting.protocol.ResponseDatagram;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ProxyInterceptor implements MethodInterceptor {
	private final String id;
	
	private final GenericObjectPool clientPool;
	
	public ProxyInterceptor(String id, GenericObjectPool clientPool) {
		this.id = id;
		this.clientPool = clientPool;
	}

	@Override
	public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if(method.isBridge() || method.getDeclaringClass() == Object.class) {
			return null;
		}
		
		RequestDatagram datagram = RequestDatagramParser.parseRequestInfo(id, method, args);
		
		RequestSendClient client = (RequestSendClient) clientPool.borrowObject();
		
		ResponseDatagram response = client.sendRequest(datagram);
		
		Object result = response.getResult();
		
		return result;
	}
	
}